package com.example.first.activities;



import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.example.first.R;
import com.example.first.modle.ApiResponse;
import com.example.first.modle.UsersVO;
import com.example.first.services.ApiService;
import com.example.first.utils.RetrofitClient;
import com.example.first.utils.Utils;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class PersonActivity extends AppCompatActivity {
    //用来标识这是选择图片的操作
    public static final int CHOOSE_PHOTO = 1;
    //用于标识申请的是什么权限
    public static final int STORAGE_PERMISSION = 1;

    public Integer flag=null;

    private File file=null;

    //标识发送哪个请求(作为参数)
    private static final int USER_IMAGE_REQUEST=1;
    private static final int BACKGROUND_REQUEST = 2;





    //返回按钮
    private ImageButton back;
    //地址管理
    private LinearLayout address;
    //历史订单
    private LinearLayout order;
    //背景
    private ImageView background;
    //头像
    private ImageView image;


    //存储用户信息
    private UsersVO user;





    private ActivityResultLauncher<Intent> mGetContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.person);

        // 设置 Toolbar 标题
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("外卖订餐");
        }


        // 设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#FFC300")); // 设置为你想要的颜色
        }


        //返回
        back = findViewById(R.id.back);
        back.setOnClickListener(v -> finish());

        //获取用户信息
        getUserInfo();





        // 注册 ActivityResultLauncher
        mGetContent = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            Intent data = result.getData();
                            if (data != null) {

                                if(flag==BACKGROUND_REQUEST){

                                background.setImageURI(data.getData());
                                }else {
                                    image.setImageURI(data.getData());
                                }

                                String realPath = Utils.getRealPath(PersonActivity.this, data);
                                file=new File(realPath);

                                // 验证文件类型是否为图片
                                if (!isImageFile(file)) {
                                    Toast.makeText(PersonActivity.this, "请选择一个图片文件", Toast.LENGTH_SHORT).show();
                                    file = null; // 清空文件对象
                                    return;
                                }


                                uploadImage(file,flag);


                            }
                        }
                    }
                });

        //背景
        background = findViewById(R.id.background_image);
        background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (Environment.isExternalStorageManager()) {
                        //获取到了权限
                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                        intent.setType("image/*");
                        flag=BACKGROUND_REQUEST;
                        mGetContent.launch(intent); // 打开本地存储

                    } else {
                        Intent intent = new Intent(
                                Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);

                    }
                }else if (ContextCompat.checkSelfPermission(PersonActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //没有获取到权限
                    ActivityCompat.requestPermissions(PersonActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
                } else {
                    Intent intent = new Intent("android.intent.action.GET_CONTENT");
                    intent.setType("image/*");
                    flag=BACKGROUND_REQUEST;
                    mGetContent.launch(intent); // 打开本地存储
                }


            }
        });

        //用户头像
        image = findViewById(R.id.user_image);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出是否更换头像的对话框
                // 创建一个确认对话框
                new AlertDialog.Builder(PersonActivity.this)
                        .setTitle("更换头像")
                        .setMessage("是否更换头像？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 用户点击确定
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                                    if (Environment.isExternalStorageManager()) {
                                        //获取到了权限
                                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                                        intent.setType("image/*");
                                        flag=USER_IMAGE_REQUEST;
                                        mGetContent.launch(intent); // 打开本地存储

                                    } else {
                                        Intent intent = new Intent(
                                                Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                                        intent.setData(Uri.parse("package:" + getPackageName()));
                                        startActivity(intent);

                                    }
                                }else if (ContextCompat.checkSelfPermission(PersonActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                    //没有获取到权限
                                    ActivityCompat.requestPermissions(PersonActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
                                } else {
                                    Intent intent = new Intent("android.intent.action.GET_CONTENT");
                                    intent.setType("image/*");
                                    flag=USER_IMAGE_REQUEST;
                                    mGetContent.launch(intent); // 打开本地存储
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        address=findViewById(R.id.address_manage);
        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(PersonActivity.this, AddressActivity.class);
                startActivity(intent);
            }
        });

        order=findViewById(R.id.history_order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(PersonActivity.this, HistoryOrderActivity.class);
                startActivity(intent);
            }
        });





    }

    //获取用户信息
    private void getUserInfo(){
        ApiService apiService= RetrofitClient.getApiService();
        Call<ApiResponse<UsersVO>> call=apiService.getUserInfo();
        call.enqueue(new Callback<ApiResponse<UsersVO>>() {
            @Override
            public void onResponse(Call<ApiResponse<UsersVO>> call, Response<ApiResponse<UsersVO>> response) {
                if(response.isSuccessful() && response.body()!=null){
                    if(response.body().getCode()==1){
                        //成功
                        user=response.body().getData();

                        if (user!=null) {
                            background=findViewById(R.id.background_image);
                            //使用Glide加载图片
                            Glide.with(PersonActivity.this)
                                    .load(user.getBackgroundImage())
                                    .into(background);

                            //加载头像
                            image=findViewById(R.id.user_image);
                            Glide.with(PersonActivity.this)
                                    .load(user.getImage())
                                    .into(image);
                        }

                    }else {
                        Toast.makeText(PersonActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }

                }
            }
            @Override
            public void onFailure(Call<ApiResponse<UsersVO>> call, Throwable t) {
                //处理失败情况
                Toast.makeText(PersonActivity.this, "请求失败", Toast.LENGTH_SHORT);
            }
        });
    }

    // 验证文件是否为图片
    private boolean isImageFile(File file) {
        String mimeType = getMimeType(file.getName());
        return mimeType != null && mimeType.startsWith("image/");
    }

    // 获取 MIME 类型的方法
    private String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
        }
        return type;
    }

    // 上传图片的方法
    private void uploadImage(File file,int requestType) {
        // 创建 RequestBody
        RequestBody requestFile = RequestBody.create(MediaType.parse(getMimeType(file.getName())), file);

        // 创建 MultipartBody.Part
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        // 调用上传接口
        ApiService apiService= RetrofitClient.getApiService();
        Call<ApiResponse<String>> call;
        //根据不同点击事件发送不同请求
        switch (requestType){
            case USER_IMAGE_REQUEST:{
                call=apiService.uploadImage(body);
                break;
            }
            case BACKGROUND_REQUEST:{
                call=apiService.uploadBackgroundImage(body);
                break;
            }
            default:{
                return;
            }
        }

        call.enqueue(new Callback<ApiResponse<String>>() {
            @Override
            public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                if(response.isSuccessful() && response.body()!=null){
                    if(response.body().getCode()==1){
                        Toast.makeText(PersonActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(PersonActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT);
                    }
                }
            }
            @Override
            public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                //处理失败情况
                Toast.makeText(PersonActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });

    }












}